package cn.ren.cloud.mq.listener;

import cn.ren.cloud.domain.CourseOrder;
import cn.ren.cloud.dto.CourseOrderPayDto;
import cn.ren.cloud.service.ICourseOrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author 23508
 */
@Slf4j
@Component
@RocketMQTransactionListener(txProducerGroup = "order-pay-group")
public class OrderPayGroupListener implements RocketMQLocalTransactionListener {


    private final ICourseOrderService courseOrderService;

    public OrderPayGroupListener(ICourseOrderService courseOrderService) {
        this.courseOrderService = courseOrderService;
    }

    /**
     * 本地事务执行器
     *
     * @param message
     * @param tag
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object tag) {
        try {
            // 如果为空直接回滚
            if (tag == null) {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            // 使用JSON转成string类型赋值给课程订单
            CourseOrder courseOrder = JSON.parseObject(JSON.toJSONString(tag), CourseOrder.class);
            // 添加订单详情
            courseOrderService.insertOrderAndItem(courseOrder);
            // 返回提交
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /**
     * 本地事务回调器
     *
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 获取内容
        byte[] payload = (byte[]) message.getPayload();
        if (payload.length == 0) {
            // 如果为空回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        // 使用JSON转成string类型赋值给CourseOrderPayDto
        CourseOrderPayDto courseOrderPayDto = JSON.parseObject(new String(payload, StandardCharsets.UTF_8), CourseOrderPayDto.class);
        // 使用支付表的订单号去回查订单表的订单号
        CourseOrder courseOrder = courseOrderService.selectByOrderNo(courseOrderPayDto.getOrderNo());
        if (courseOrder == null) {
            // 如果为空回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        // 否则提交
        return RocketMQLocalTransactionState.COMMIT;
    }
}
